<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/7
 * Time: 14:25
 */

namespace zhtfrontend\controllers;


use common\components\helpers\Tree;
use common\models\datas\Cate;
use doumiaoduo\buildform\BuildForm;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\CateRelation;
use zhtfrontend\models\datas\Classroom;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\BadRequestHttpException;
use zhtfrontend\models\datas\ClassroomGroup;
use zhtfrontend\models\datas\Mechanic;
use yii\data\Pagination;
use yii\helpers\Json;

class ClassroomController extends BaseController
{

    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $classroom = Classroom::find()->orderBy('name ASC');
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['name'])) {
                $classroom->andWhere(['like', 'name', $search_data['name']]);
            }
            if (!empty($search_data['room_number'])) {
                $classroom->andWhere(['like', 'room_number', $search_data['room_number']]);
            }
            if (!empty($search_data['searchWay'])) {
                if ($search_data['searchWay'] == 2) {
                    $search_data['searchWay'] = 0;
                }
                $classroom->andWhere(['state' => $search_data['searchWay']]);
            }
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'business_director') {
            $DirectorMechanicIds = Fun::getDirectorMechanicIds();
            $classroom->andWhere(['mechanic_id' => $DirectorMechanicIds]);
        }
        $pages = new Pagination(['totalCount' => $classroom->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $classroom = $classroom->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($classroom, ['admin', 'mechanic_name', 'zhtfrontend_operate']);

        return $this->render('index',['data'=>$array,'pages'=>$pages]);
    }

    /*
     * 教室添加
     */
    public function actionCreate()
    {
        $model = new Classroom();
        $model->is_share = 0;
        $cate = Cate::find()->where(['is_show' => 1, 'is_delete' => 0])->indexBy('id')->all();
        $tree_cate = (new Tree($cate))->get_tree_select();
        $cate_checked = [];

        $roomGroup = ClassroomGroup::find()->all();
        $roomGroup = ArrayHelper::map($roomGroup, 'id', 'name');
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
            $model->user_id = \Yii::$app->user->id;
//            $model->share_count > 1 ? $model->is_share = 1 : $model->is_share = 0;
            if ($model->save(false)) {
                $cate_id = array_unique($post['Classroom']['classroom_cates']);
                foreach ($cate_id as $k => $v) {
                    $cate_relation = new CateRelation();
                    $cate_relation->object_id = $model->id;
                    $cate_relation->cate_id = $v;
                    $cate_relation->type = 2;
                    $cate_relation->save(false);
                }
                return $this->redirectMessage('添加成功', Fun::url(['classroom/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'cate' => $tree_cate, 'cate_checked' => $cate_checked, 'roomGroup' => $roomGroup]);
    }

    /*
     * 教室修改
     */
    public function actionUpdate()
    {
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = Classroom::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $roomGroup = ClassroomGroup::find()->all();
        $roomGroup = ArrayHelper::map($roomGroup, 'id', 'name');
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        $cate = Cate::find()->where(['is_show' => 1, 'is_delete' => 0])->indexBy('id')->all();
        $tree_cate = (new Tree($cate))->get_tree_select();
        $cate_check = CateRelation::find()->where(['object_id' => $id,'type'=>2])->all();
        $cate_checked = [];
        foreach ($cate_check as $k => $v) {
            $cate = Cate::findOne([$v->cate_id]);
            $cate_checked[$v->cate_id] = $cate->name;
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $post = \Yii::$app->request->post();
//            $model->share_count > 1 ? $model->is_share = 1 : $model->is_share = 0;
            if ($model->save(false)) {
                CateRelation::deleteAll(['and','object_id=:id','type=:type'], [':id' => $model->id,':type'=>2]);
                $cate_id = array_unique($post['Classroom']['classroom_cates']);
                foreach ($cate_id as $k => $v) {
                    $cate_relation = new CateRelation();
                    $cate_relation->object_id = $model->id;
                    $cate_relation->cate_id = $v;
                    $cate_relation->type = 2;
                    $cate_relation->save(false);
                }
                return $this->redirectMessage('修改成功', Fun::url(['classroom/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'cate_checked' => $cate_checked, 'cate' => $tree_cate, 'roomGroup' => $roomGroup]);
    }

    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Classroom::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        Fun::getSiteDb()->createCommand()->delete('{{%classroom_attr}}', "classroom_id = $model->id")->execute();
        if ($model->delete()) {
            return $this->redirectMessage(\Yii::t('zhtfrontend', '信息删除成功'), Fun::url(['classroom/index']));
        }
    }
}
